package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
@Autowired
    FileStorageService fileStorageService;
@Value("${file.oss.prefix}")
String prefix;
@Value("${file.oss.web-site}")
String website;

    /**
     * 上传图片到oss
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1.检查参数
        if (multipartFile.isEmpty() || multipartFile.getSize()==0 ){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的文件");
        }
        //从线程中获取当前用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"未登录");
        }
        //上传文件到阿里云OSS


        //获取原始文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        //文件名称： 获取原始的后缀  meinv.jpg  .jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //新文件名称;随机生成的uuid+后缀
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        //新文件名称
        String fileName =uuid+suffix;

        //调用上传方法
        try {
            //文件在oss中的全路径
            String store = fileStorageService.store(prefix, fileName, multipartFile.getInputStream());
            //创建Material实体类
            WmMaterial wmmaterial = new WmMaterial();
            wmmaterial.setUserId(user.getId());//用户登录id
            wmmaterial.setUrl(store);//在oss中访问全路径
            wmmaterial.setType((short)0);
            wmmaterial.setIsCollection((short)0);
            wmmaterial.setCreatedTime(new Date());

            //保存素材
            save(wmmaterial);
            //返回结果，需要在url加访问前缀，用于前端回显数据
            wmmaterial.setUrl(website+wmmaterial.getUrl());
            return ResponseResult.okResult(wmmaterial);

        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传文件失败==》{}",e.getMessage());
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"服务端出现异常上传失败");
        }

    }

    /**
     * 素材列表查询实现方法
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //参数校验
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //封装查询参数
        Page<WmMaterial> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //查询参数
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.lambdaQuery();
        //收藏
        if (dto.getIsCollection()!=null && dto.getIsCollection()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //当前用户登录素材
        lambdaQueryWrapper.eq(WmMaterial::getUserId,user.getId());
        //按照发布时间降序排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //封装查询结果
        IPage<WmMaterial> pageResult = page(pageReq, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());

        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(website+record.getUrl());
        }
        responseResult.setData(records);
        return responseResult;
    }


    /**
     * 删除素材
     */
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    //WmMaterialMapper wmMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        //校验参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询素材是否被引用 id 素材id 文章id，如果被使用则禁止删除
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null){//素材不为空
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);

        Integer count = wmNewsMaterialMapper.selectCount(queryWrapper);
        if (count>0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        // 2. 查询该素材是否被引用   id  素材id   文章id
       /* Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if(count > 0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"素材已被引用，无法删除");
        }*/

        //删除素材库
        removeById(id);
        //删除OSS图片
        fileStorageService.delete(wmMaterial.getUrl());


        return ResponseResult.okResult("删除成功");
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //检查参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //更新状态
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, type)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, user.getId())
        );
        return ResponseResult.okResult();
    }

}
